/**
 * 
 */
package biz.innovasoft.nodb.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import biz.innovasoft.nodb.DeleteObjectException;
import biz.innovasoft.nodb.DeleteValidator;
import biz.innovasoft.nodb.RepositoryException;
import biz.innovasoft.nodb.ValidationException;
import biz.innovasoft.nodb.query.Tuple;

/**
 * 
 * @author Diego Miranda
 *
 */
public class DeleteHelper implements Serializable {

	private static final long serialVersionUID = 6995664671961776157L;
	
	private GenericRepository repository;
	
	public DeleteHelper (GenericRepository repository) {
		this.repository = repository;
	}
	
	public Object delete(Long oid, boolean indexNow) throws RepositoryException {
		if (!repository.getObjects().containsKey(oid)) {
			throw new DeleteObjectException(
					"Trying to delete an object with an inexistent key. OID: "
							+ oid);
		}
		
		validate (oid, repository.getByOId(oid));
		
		Object object = repository.getObjects().remove(oid);
		repository.availableOids.push(oid);
		repository.getIndexHelper().deleteIndexObject(oid, object);
		return object;

	}
	
	public void delete (Long[] oids) throws RepositoryException {
		for (Long oid : oids) {
			delete (oid, true);
		}
	}
	
	public void delete (Class<?> clazz) {
		List<Tuple>tuples = repository.getAll(clazz);
		for (Tuple tuple : tuples) {
			delete (tuple.oid, true);
		}
		repository.removeStoredClass(clazz);
	}
	
	private void validate (Long oid, Object object) {
		Map<String,DeleteValidator> validators = repository.getDeleteValidator(object.getClass());
		if ( validators == null ) {
			return;
		}
		for (String key : validators.keySet()) {
			DeleteValidator validator = validators.get(key);
			if (!validator.canDelete(object)) {
				throw new ValidationException ("Object cant be stored. Validator: " + key + " has failed.", oid, key);
			}
		}
	}

}
